<template>
  <div class="mobile-apps">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="header-title">应用中心</div>
      <!-- Add Edit/Done button -->
      <div class="header-right" @click="toggleEditMode">
        {{ isEditing ? '完成' : '编辑' }}
      </div>
    </div>

    <!-- 直接展示所有模块 -->
    <div class="app-content-full" :class="{ 'is-editing': isEditing }">
      <!-- Loop through application modules (Finance, Material, Asset) -->
      <div v-for="module in modules" :key="module.id" class="module-section">
        <div class="section-header">
          <div class="section-title">
            <van-icon :name="module.icon" :color="module.color" />
            <span>{{ module.title }}</span>
          </div>
        </div>
        <div class="app-grid">
          <!-- Loop through functions within the module -->
          <div v-for="app in module.apps" :key="app.id" class="app-item" :class="{ placeholder: app.placeholder }" @click="!isEditing && !app.placeholder ? navigateTo(app.path) : null">
            <div class="app-icon" :class="app.iconBg">
              <van-icon :name="app.icon" size="24" />
              <!-- Add button overlay: Show only in edit mode, if not placeholder, and not already added -->
              <div 
                v-if="isEditing && !app.placeholder && !isFunctionAdded(app.id)"
                class="add-overlay"
                @click.stop="addCommonFunction(app)"
              >
                <van-icon name="plus" size="18" />
              </div>
              <!-- Optional: Added state indicator (could be shown in edit mode too) -->
              <div 
                v-if="isEditing && !app.placeholder && isFunctionAdded(app.id)"
                class="added-overlay"
                title="已添加"
              >
                <van-icon name="success" size="18" />
              </div>
            </div>
            <div class="app-name">{{ app.name }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部导航栏 -->
    <van-tabbar v-model="activeTabbar" route>
      <van-tabbar-item name="home" icon="home-o" to="/new/home">首页</van-tabbar-item>
      <van-tabbar-item name="apps" icon="apps-o" to="/new/apps">应用</van-tabbar-item>
      <van-tabbar-item name="profile" icon="user-o" to="/new/profile">我的</van-tabbar-item>
    </van-tabbar>

  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import {
  Icon, Tabbar, TabbarItem, Toast
} from 'vant'

export default {
  name: 'MobileApplications',
  components: {
    vanIcon: Icon,
    vanTabbar: Tabbar,
    vanTabbarItem: TabbarItem
  },
  setup() {
    const router = useRouter()
    const store = useStore()

    const activeTabbar = ref('apps')
    const isEditing = ref(false) // State for edit mode

    // Toggle edit mode
    const toggleEditMode = () => {
      isEditing.value = !isEditing.value;
    }

    // Get function list from Vuex to check if already added
    const commonFunctionList = computed(() => store.state.mobile.functionList);
    const commonFunctionIds = computed(() => new Set(commonFunctionList.value.map(f => f.id)));

    // Function to check if a function ID exists in the common list
    const isFunctionAdded = (id) => {
      return commonFunctionIds.value.has(id);
    }

    // Method to add a function to common functions (dispatch Vuex action)
    const addCommonFunction = (func) => {
      // We need the function object as defined in allAvailableFunctions (with the correct id)
      // Find the corresponding function definition from the store
      const functionToAdd = store.state.mobile.allAvailableFunctions.find(f => f.path === func.path || f.id === func.id); 
      if (functionToAdd) {
         console.log("Adding from App Center:", functionToAdd);
         store.dispatch('mobile/addFunction', functionToAdd)
          .then(() => {
             Toast.success(`${functionToAdd.name} 已添加到常用功能`);
          })
          .catch(error => {
             console.error("Error adding function from App Center:", error);
             Toast.fail('添加失败');
          });
      } else {
          console.warn("Could not find function definition in store for:", func);
          Toast.fail('无法添加此功能');
      }
    }

    // Define modules and their apps (use IDs from allAvailableFunctions)
    // This structure helps in rendering the template loop
    const modules = computed(() => [
      {
        id: 'finance',
        title: '财务应用',
        icon: 'balance-o',
        color: '#1A7BB9',
        apps: [
          { id: 'finance-expense', name: '费用报销', icon: 'balance-list-o', path: '/new/finance/expense', iconBg: 'blue' },
          { id: 'finance-invoice', name: '发票管理', icon: 'bill-o', path: '/new/finance/invoice', iconBg: 'blue' },
          { id: 'finance-salary', name: '工资查询', icon: 'gold-coin-o', path: '/new/finance/salary', iconBg: 'blue' },
          { id: 'finance-budget', name: '预算管理', icon: 'chart-trending-o', path: '/new/finance/budget', iconBg: 'blue' },
          { id: 'finance-travel-apply', name: '出差申请', icon: 'logistics', path: '/new/finance/travel/apply', iconBg: 'blue' },
          { id: 'finance-travel-list', name: '我的出差', icon: 'notes-o', path: '/new/finance/travel/list', iconBg: 'blue' },
          { id: 'finance-apply', name: '财务申请', icon: 'cash-o', path: '/new/finance/application', iconBg: 'blue' },
          { id: 'finance-standard', name: '差旅标准', icon: 'description', path: '/new/finance/travel-standard', iconBg: 'blue' },
          { id: 'finance-travel-expense', name: '差旅报销', icon: 'balance-pay', path: '/new/finance/travel-expense', iconBg: 'blue' },
        ]
      },
      {
        id: 'material',
        title: '物资应用',
        icon: 'shopping-cart-o',
        color: '#4CB050',
        apps: [
          { id: 'material-apply', name: '物资申领', icon: 'shopping-cart-o', path: '/new/material/apply', iconBg: 'green' },
          { id: 'material-list', name: '库存查询', icon: 'list-switch', path: '/new/material/list', iconBg: 'green' },
          { id: 'material-inbound', name: '采购验收', icon: 'down', path: '/new/material/inbound', iconBg: 'green' },
          { id: 'material-outbound', name: '调拨验收/出库', icon: 'upgrade', path: '/new/material/outbound', iconBg: 'green' },
          { id: 'material-inventory', name: '物资盘点', icon: 'todo-list-o', path: '/new/material/inventory', iconBg: 'green' },
          { id: 'material-consumption', name: '物资消费', icon: 'chart-trending-o', path: '/new/material/consumption', iconBg: 'green' }, 
        ]
      },
      {
        id: 'asset',
        title: '资产应用',
        icon: 'desktop-o',
        color: '#8E24AA',
        apps: [
          { id: 'asset-list', name: '资产列表', icon: 'records', path: '/new/asset/list', iconBg: 'purple' },
          { id: 'asset-apply', name: '资产领用', icon: 'edit', path: '/new/asset/apply', iconBg: 'purple' },
          { id: 'asset-repair', name: '资产维修', icon: 'setting-o', path: '/new/asset/repair', iconBg: 'purple' },
          { id: 'asset-inventory', name: '资产盘点', icon: 'list-o', path: '/new/asset/inventory', iconBg: 'purple' },
          { id: 'asset-dispose', name: '资产处置', icon: 'delete-o', path: '/new/asset/dispose', iconBg: 'purple' },
          { id: 'asset-transfer', name: '资产调拨', icon: 'exchange', path: '/new/asset/transfer', iconBg: 'purple' },
        ]
      }
    ]);

    // 导航方法
    const navigateTo = (path) => {
      if (isEditing.value) return; // Disable navigation in edit mode
      if (!path || path === '#') {
        Toast('功能暂未开放'); // 使用Toast提示
        console.warn('功能暂未开放或路径无效:', path)
        return;
      }
      router.push(path)
       store.dispatch('mobile/recordVisit', {
        path,
        name: path.split('/').pop(),
        icon: getIconForPath(path),
        iconBg: getColorForPath(path),
        time: new Date().toLocaleString('zh-CN', { /* ... */ })
      })
    }

    // 根据路径获取图标 (辅助函数)
    const getIconForPath = (path) => {
      if (path.includes('/finance')) return 'balance-o';
      if (path.includes('/material')) return 'shopping-cart-o';
      if (path.includes('/asset')) return 'desktop-o';
      return 'apps-o';
    }

    // 根据路径获取颜色 (辅助函数)
    const getColorForPath = (path) => {
      if (path.includes('/finance')) return 'blue';
      if (path.includes('/material')) return 'green';
      if (path.includes('/asset')) return 'purple';
      return 'cyan';
    }

    return {
      activeTabbar,
      isEditing,        // Expose editing state
      toggleEditMode,   // Expose method to toggle edit mode
      modules,
      navigateTo,
      isFunctionAdded,
      addCommonFunction
    }
  }
}
</script>

<style scoped>
.mobile-apps {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 50px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between; /* Align items with space between */
  height: 44px;
  background-color: #ffffff;
  color: #333333;
  padding: 0 16px;
  font-weight: 500;
  position: sticky;
  top: 0;
  z-index: 11;
  border-bottom: 1px solid #f0f0f0;
}

.header-title {
  font-size: 18px;
}

.header-right {
  font-size: 14px;
  color: #1A7BB9; /* Match homepage edit button color */
  cursor: pointer;
  padding: 0 8px; /* Add some padding */
}

.app-content-full {
  padding: 12px 16px; /* 给整体内容区域添加内边距 */
}

.module-section {
  margin-bottom: 16px; /* 调整模块间距 */
  background-color: #ffffff;
  border-radius: 8px;
   box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
   padding-bottom: 8px;
   /* 防止最后一个模块底部没有间距 */
   &:last-child {
     margin-bottom: 0;
   }
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 15px;
  font-weight: 500;
}

.section-title .van-icon {
  margin-right: 6px;
}

.app-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px 8px;
  padding: 16px;
}

.app-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.app-icon {
  position: relative; /* Needed for overlay positioning */
  width: 44px;
  height: 44px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 6px;
  color: white;
  transition: transform 0.2s;
}
.app-icon:active {
   transform: scale(0.95);
}

.app-icon.blue { background-color: #1A7BB9; }
.app-icon.green { background-color: #4CB050; }
.app-icon.orange { background-color: #FF9800; }
.app-icon.purple { background-color: #8E24AA; }
.app-icon.cyan { background-color: #00BCD4; }
.app-icon.red { background-color: #E53935; }
.app-icon.gray { background-color: #bdc3c7; }

.app-name {
  font-size: 12px;
  color: #323233;
  line-height: 1.3;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.app-item.placeholder .app-name {
  color: #969799;
}
.app-item.placeholder .app-icon {
  opacity: 0.7;
}

.add-overlay {
  position: absolute;
  top: -5px;  /* Position slightly offset */
  right: -5px; /* Position slightly offset */
  width: 20px;
  height: 20px;
  background-color: rgba(0, 128, 0, 0.8); /* Green background for add */
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  transition: background-color 0.2s, transform 0.2s;
}

.add-overlay:hover {
  background-color: rgba(0, 128, 0, 1); /* Darker green on hover */
  transform: scale(1.1);
}

/* Styles for added state indicator (checkmark) */
.added-overlay {
  position: absolute;
  top: -5px;
  right: -5px;
  width: 20px;
  height: 20px;
  background-color: rgba(76, 175, 80, 0.7); /* Green background for added */
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: default; /* Not clickable by default */
}

/* Prevent app item click in edit mode if needed (already handled in navigateTo) */
/* 
.is-editing .app-item {
  cursor: default;
}
*/

.van-tabbar {
  z-index: 10;
}
</style>
